<?php
// +----------------------------------------------------------------------
// | 双擎码防伪溯源系统 [ 致力于通过产品和服务，帮助商家开启标准化全链路商品溯源 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009~2024 https://www.sqm.la All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 双擎科技 <yjw@sqm.la>
// +----------------------------------------------------------------------
namespace app\sys\controller;

use think\admin\Controller;
use think\admin\service\InterfaceService;
use think\admin\model\SysDevelop;

/**
 * 接口授权基础控制器
 * Class Auth
 * @package app\sys\controller
 */
class Auth extends Controller
{
    /**
     * 当前请求数据
     * @var array
     */
    protected $data;

    /**
     * 接口ID
     * @var string
     */
    protected $appid = '接口账号';

    /**
     * 接口密钥
     * @var string
     */
    protected $appkey = '接口密钥';

    /**
     * 接口服务对象
     * @var InterfaceService
     */
    protected $interface;

    /**
     * 接口授权初始化
     */
    protected function initialize()
    {
        // 接口数据初始化
        $this->interface = InterfaceService::instance();
        // 从数据库中账号检查
        $postData = $this->_vali(['data.require' => '参数不能为空！']);
        $map = json_decode($postData['data'],true);
        $this->user = SysDevelop::mk()->where($map)->findOrEmpty()->toArray();
        if (empty($this->user)) $this->error('接口账号不存在！');
        if (!empty($this->user['status'])) $this->error('接口账号已被禁用！');
        if (!empty($this->user['isDeleted'])) $this->error('接口账号已被移除！');

        $this->interface->setAuth($this->user['appId'], $this->user['appKey']);
        [$this->data, $this->appid] = [$this->interface->getData(), $this->interface->getAppid()];
    }

    /**
     * 响应错误消息
     * @param mixed $info
     * @param string $data
     * @param int $code
     * @param bool $success
     */
    public function error($info, $data = '{-null-}', $code = 0, $success = false): void
    {
        $this->interface->error($success, $code, $info, $data);
    }

    /**
     * 响应成功消息
     * @param mixed $info
     * @param string $data
     * @param int $code
     * @param bool $success
     */
    public function success($info, $data = '{-null-}', $code = 200, $success = true): void
    {
        $this->interface->success($success, $info, $data, $code);
    }

    /**
     * 响应高级数据
     * @param array $data
     */
    protected function response(array $data = []): void
    {
        $this->interface->baseSuccess('接口调用成功！', $data);
    }
}
